// 中间件，洋葱模型做权限校验
const { verifyToken } = require('../util/jwt')


exports.checkAuth = function (secretKey) {
    return (req, res, next) => {
        const authHeader = req.headers['authorization']
        // const token = authHeader && authHeader.split(' ')[1]
        if (!authHeader) {
            return res.send({
                code: 401,
                msg: "请先登录"
            })
        }
        const token = authHeader.split(' ')[1]
        // 验证token
        const claim = verifyToken(token, secretKey)
        if (claim === null) {
            return res.send({
                code: 401,
                msg: "请先登录"
            })
        }
        req.claim -= claim
        next()
    }
}